package Servlet;

import Bean.UserBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 黄忠
 * 创建于2019-06-01
 */


@WebServlet("/upload")
@MultipartConfig(location = "E:\\JavaProjects\\ShiYan4\\src\\main\\webapp\\images")// location为项目相对地址的绝对地址
public class UploadFileServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        HttpSession session = request.getSession(true);
        UserBean userBean=(UserBean) session.getAttribute("UserBean");
        if(userBean!=null){
            Part part = request.getPart("tx");
            String fileName = part.getSubmittedFileName();
            System.out.println("上传文件的文件名: " + fileName);
            String [] nameSplit= fileName.split("\\.");
            if(nameSplit.length==0){
                response.getWriter().write("<script>alert('你再这样就封号了!');location.href='http://localhost:8080/infor.jsp'</script>");
                return;
            }
            String format = nameSplit[nameSplit.length-1];
            if(!(format.equalsIgnoreCase("jpg")||format.equalsIgnoreCase("png"))){
                response.getWriter().write("<script>alert('仅支持jpg和png格式图片!');location.href='http://localhost:8080/infor.jsp'</script>");
                return;
            }
            Date d = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String now = df.format(d);
            fileName = now+"."+nameSplit[nameSplit.length-1];
            String filePar = "E:\\JavaProjects\\ShiYan4\\src\\main\\webapp\\images\\"+userBean.getUsername();// 文件夹路径
            File myPath = new File(filePar);
            if (!myPath.exists()){//若此目录不存在，则创建之
                myPath.mkdir();
                System.out.println("创建文件夹路径为："+ filePar);
            }
            part.write(userBean.getUsername()+"\\"+fileName);
            userBean.setTX(fileName);
            session.setAttribute("UserBean",userBean);
            response.sendRedirect("http://localhost:8080/infor.jsp");
        }
        else response.sendRedirect("http://localhost:8080/login.jsp");
    }
}